package com.lyc.mall.filter;

import com.google.gson.Gson;
import com.lyc.mall.util.Constant;
import com.lyc.mall.util.Result;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/api/admin/*")
public class AdminFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        // 允许访问的来源的域
        // 如果允许浏览器携带cookie，服务器端必须设置此项为前端的主机名+端口号
        response.setHeader("Access-Control-Allow-Origin", Constant.ORIGIN);
        // 允许发送的请求的方法
        response.setHeader("Access-Control-AllowMethods", "POST,GET,OPTIONS,PUT,DELETE");
        // 发送请求时允许携带的头
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization,Content-Type");
        // 是否允许携带cookie的凭证
        response.setHeader("Access-Control-Allow-Credentials", "true");
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        // 业务逻辑：除登陆之外的所有接口，都应当加上权限。登录之后可以自由访问
        // 如果访问的不是login页面
        if (!(request.getContextPath() + "/api/admin/admin/login").equals(request.getRequestURI())) {
            // 查询是否登录
            HttpSession session = request.getSession();
            // 跨域请求时需要前后端均开启跨越
            Object email = session.getAttribute("email");
            // 未登录
            if (email == null) {
                response.getWriter().println(new Gson().toJson(Result.ERROR("当前接口仅登陆后访问")));
                return;
            }
        }
        // 否则放行
        chain.doFilter(request, response);
    }
}
